﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using EzDesk.Apps.Model.Message;
using EzDesk.Utility;
using System.Xml.Linq;
using System.Text;
using EzDesk.EzAppApi.Utility;
using EzDesk.Utility.Web.Controllers;
using EzDesk.Apps.Model.Message;
using EzDesk.Core.Model;
using EzDesk.Utility.Log;
using System.Text.RegularExpressions;
using EzDesk.Clients.MobileWeb.TopicService;
using EzDesk.Utility.Web.Extensions;
using EzDesk.Utility.Web.ServiceReference;

namespace EzDesk.Clients.MobileWeb.Controllers
{
    public class MessageController : EzDeskAppController
    {
        static ITopicService TopicService
        {
            get { return ServiceReferenceFactory<ITopicService, TopicServiceClient>.GetService(); }
        }

        [HttpGet]
        public ActionResult Index()
        {
            //    ViewData["latestMessages"] = topicService.GetMessages(CurrentUserId, null, 0, 5);
            //    ViewData["sentMessages"] = topicService.GetMessages(null, CurrentUserId, 0, 5);
            return View();
        }

        [HttpGet]

        public ActionResult SendPublic()
        {
            return View();
        }



        public ActionResult Send(Guid? deptId)
        {
            List<Dept> deptToChooseList = new List<Dept>();
            deptToChooseList.Add(
                new Dept()
                {
                    DeptName = "==所有部门==",
                    Id = Guid.Empty,
                }
                );
            deptToChooseList.AddRange(
                EzApiClient.GetAllDepts()
                );

            var deptListSelectItem = new SelectList(
                deptToChooseList,
                "Id",
                "DeptName",
                deptId.GetValueOrDefault(Guid.Empty)
                );

            IList<SimpleUser> usersToChooseList = TopicService.GetPersonsInDept(deptId);

            ViewData["deptId"] = deptListSelectItem;
            ViewData["usersToChooseList"] = usersToChooseList;
            return View();
        }

        [HttpGet]

        public ActionResult Show(Guid topicId)
        {
            //todo: 异常处理
            var topic = TopicService.GetFullTopic(topicId, CurrentUserId);
            topic.MessageText = topic.MessageText.RemoveHtml();
            // 判断是否有权限查看)

            return View(topic);
        }



        [HttpGet]

        public ActionResult ReplySingle(Guid messageId)
        {
            var singleMessage = TopicService.GetSingleMessage(messageId);

            return View(singleMessage);
        }

        [HttpGet]

        public ActionResult Confirm(Guid topicId)
        {
            //todo: 异常处理
            var topic = TopicService.GetFullTopic(topicId, CurrentUserId);

            return View(topic);
        }





        /// <summary>
        /// 确认一个消息，如果没有返回地址则返回消息本身
        /// </summary>
        /// <param name="messageId">要确认的消息ID</param>
        /// <param name="returnUrl">确认后返回的Url</param>
        /// <returns></returns>

        public ActionResult ConfirmMessage(Guid topicId)
        {
            try
            {
                TopicService.ConfirmMessage(topicId, CurrentUserId);
            }
            catch (Exception ex)
            {
                LogEx.ERROR("[MobileWeb - Message]", "确认消息时发生错误!", ex);
            }

            SetReturnInfoText("成功确认消息。");
            return RedirectToAction("Show", new { topicId });
        }



        [HttpPost]

        public ActionResult SendAdv(IList<string> usersToSend)
        {
            if (usersToSend == null || usersToSend.Count == 0)
            {
                // 没有选择用户，返回继续选择
                SetReturnInfoText("没有选择发送对象");
                return RedirectToAction("Send");
            }

            ParticipatorsInfo participators = new ParticipatorsInfo();
            foreach (var userIdStr in usersToSend)
            {
                SimpleUser simpleUser = EzApiClient.GetSimpleUserById(new Guid(userIdStr));
                participators.UserParticipators.Add(simpleUser);
            }
            string memberString = usersToSend.Join(",");

            ViewData["participators"] = participators;
            ViewData["memberString"] = memberString;

            return View();
        }

        /// <summary>
        /// 发送公共消息
        /// </summary>
        /// <param name="messageText">消息内容</param>
        /// <param name="needConfirm">这个消息是否需要确认</param>
        /// <returns></returns>
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult SendPublicMessage(string messageText, bool needConfirm)
        {
            string memberstring = "everyone";
            string msgTextContent = messageText.RemoveSpace();
            string msgTextEncode = messageText.HtmlEncode();

            Guid senderId = CurrentUserId;

            //todo: 异常处理
            if (string.IsNullOrEmpty(msgTextContent))
            {
                SetReturnInfoText("不能发送空消息！");
                return RedirectToAction("Index");
            }
            else
            {
                Guid newMessageId = TopicService.CreateNewTopic(senderId, string.Empty, msgTextEncode, needConfirm, memberstring);

                SetReturnInfoText("新消息发布成功");
                return RedirectToAction("Show", new { topicId = newMessageId });
            }

        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult SendAdvMessage(string memberstring, string messageText, bool needConfirm)
        {
            Guid senderId = CurrentUserId;
            string msgTextContent = messageText.RemoveSpace();
            string msgTextEncode = messageText.HtmlEncode();

            if (string.IsNullOrEmpty(msgTextContent))
            {
                SetReturnInfoText("不能发送空消息！");
                return RedirectToAction("Index");
            }
            else
            {
                Guid newMessageId = TopicService.CreateNewTopic(senderId, string.Empty, msgTextEncode, needConfirm, memberstring);

                SetReturnInfoText("新消息发布成功");
                return RedirectToAction("Show", new { topicId = newMessageId });
            }
            //todo: 异常处理

        }

        /// <summary>
        /// 回复一个主题
        /// </summary>
        /// <param name="replyText">回复的内容</param>
        /// <param name="topicId">主题ID</param>
        /// <returns></returns>
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult ReplyTopic(string replyText, Guid topicId, bool isReplyToAll)
        {
            string replyContent = replyText.RemoveSpace();
            string replyTextEncode = replyText.HtmlEncode();

            Guid senderId = CurrentUserId;

            //todo: 异常处理
            if (string.IsNullOrEmpty(replyContent))
            {
                SetReturnInfoText("不能发送空消息！");
                return RedirectToAction("Index");
            }
            else
            {
                TopicService.ReplyToMessage(senderId, topicId, topicId, replyTextEncode, isReplyToAll);

                SetReturnInfoText("回复消息成功");

            }


            return RedirectToAction("Show", new { topicId });
        }

        /// <summary>
        /// 回复单条（回复）消息
        /// </summary>
        /// <param name="messageId">被回复的消息ID</param>
        /// <param name="topicId">主题的ID</param>
        /// <param name="replyText"></param>
        /// <param name="isReplyToAll"></param>
        /// <returns></returns>
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult ReplySingleMessage(Guid messageId, Guid topicId, string replyText, bool isReplyToAll)
        {
            string replyContent = replyText.RemoveSpace();
            string replyTextEncode = replyText.HtmlEncode();

            Guid senderId = CurrentUserId;

            //todo: 异常处理
            if (string.IsNullOrEmpty(replyContent))
            {
                SetReturnInfoText("不能发送空消息！");
                return RedirectToAction("Index");
            }
            else
            {
                if (TopicService != null)
                    TopicService.ReplyToMessage(senderId, messageId, topicId, replyText, isReplyToAll);
                SetReturnInfoText("回复消息成功");
            }

            return RedirectToAction("Show", new { topicId });
        }





    }
}
